package cn.tedu.mall.seckill.interceptor;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderAddDTO;
import cn.tedu.mall.pojo.seckill.vo.SeckillSpuVO;
import cn.tedu.mall.seckill.service.Impl.SeckillSpuServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 验证提交的randCode和下单商品所属spu是否匹配
 */
@Component
@Order(0)// 数字越小执行顺序越靠前
public class RandCodeInterceptor implements SeckillInterceptor{
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void seckillCommitCheck(SeckillOrderAddDTO seckillOrderAddDTO) {
        Long spuId = seckillOrderAddDTO.getSpuId();
        String spuVOKey = SeckillSpuServiceImpl.SECKILL_SPU_PREFIX + spuId;
        Object obj = redisTemplate.opsForValue().get(spuVOKey);
        if (obj == null) {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "没有spuId=" + spuId + "对应的数据，无法对比randCode");
        }
        SeckillSpuVO seckillSpuVO = (SeckillSpuVO) obj;
        String url = seckillSpuVO.getUrl();
        String randUrl = "/seckill/" + seckillOrderAddDTO.getRandCode();
        if (!Objects.equals(url, randUrl)) {
            throw new CoolSharkServiceException(ResponseCode.CONFLICT, "秒杀路径不正确！");
        }
    }
}
